//
//  ASAvatarGroupCell.m
//  AvatarShow
//
//  Created by xunruiIOS on 2021/4/29.
//

#import "ASAvatarGroupCell.h"
#import "ASHomeApi.h"
#import "BDFCustomPhotoAlbum.h"

@implementation ASAvatarGroupCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self.contentView addSubview:self.userIconImage];
        [self.contentView addSubview:self.userIconBtn];
        [self.contentView addSubview:self.userNameLab];
        [self.contentView addSubview:self.titleLab];
        [self.contentView addSubview:self.mainView];
        [self.contentView addSubview:self.labelSelect];
        [self.contentView addSubview:self.saveBtn];
        [self.contentView addSubview:self.collectionBtn];
        [self.contentView addSubview:self.lineView];
        [self setAllViewLayout];
    }
    return self;
}

- (void)setAllViewLayout{
    @weakify(self);
    [self.userIconImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(13);
        make.top.mas_equalTo(15);
        make.size.mas_equalTo(CGSizeMake(52, 52));
    }];
    
    [self.userIconBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(13);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - 70, 36));
    }];
    
    [self.userNameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.left.mas_equalTo(self.userIconImage.mas_right).mas_offset(10);
        make.top.mas_equalTo(self.userIconImage.mas_top);
        make.right.mas_equalTo(-10);
    }];
    
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.left.mas_equalTo(self.userNameLab.mas_left);
        make.top.mas_equalTo(self.userNameLab.mas_bottom).mas_offset(10);
        make.right.mas_equalTo(-10);
    }];
    
    [self.mainView mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(self.userIconImage.mas_bottom).mas_offset(15);
        make.height.mas_equalTo(100);
    }];
    
    [self.labelSelect mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.top.mas_equalTo(self.mainView.mas_bottom).mas_offset(15);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(25);
    }];
    
    [self.saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.right.mas_equalTo(-14);
        make.size.mas_equalTo(CGSizeMake(95, 30));
        make.top.mas_equalTo(self.labelSelect.mas_bottom).mas_offset(15);
    }];
    
    [self.collectionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.right.mas_equalTo(self.saveBtn.mas_left).mas_offset(-20);
        make.width.mas_equalTo(self.saveBtn.mas_width);
        make.height.mas_equalTo(self.saveBtn.mas_height);
        make.centerY.mas_equalTo(self.saveBtn.mas_centerY);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(5);
        make.top.mas_equalTo(self.collectionBtn.mas_bottom).mas_offset(10);
    }];
}

- (UIButton *)userIconBtn{
    if (!_userIconBtn) {
        _userIconBtn = [UIButton new];
        [_userIconBtn addTarget:self action:@selector(clickUserBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _userIconBtn;
}

- (UIImageView *)userIconImage{
    if (!_userIconImage) {
        _userIconImage = [UIImageView new];
        _userIconImage.layer.masksToBounds = YES;
        _userIconImage.layer.cornerRadius = 26;
        _userIconImage.contentMode = UIViewContentModeScaleAspectFill;
        _userIconImage.clipsToBounds = YES;
        _userIconImage.layer.borderColor = [UIColor colorWithHexString:@"#FF7785"].CGColor;
        _userIconImage.layer.borderWidth = 1.f;
    }
    return _userIconImage;
}

- (UILabel *)userNameLab{
    if (!_userNameLab) {
        _userNameLab = [UILabel new];
        _userNameLab.font = [UIFont systemFontOfSize:16];
        _userNameLab.textColor = [UIColor colorWithHexString:@"#FF7785"];
    }
    return _userNameLab;
}

- (UILabel *)titleLab{
    if (!_titleLab) {
        _titleLab = [UILabel new];
        _titleLab.font = [UIFont systemFontOfSize:15];
        _titleLab.textColor = [UIColor colorWithHexString:@"#1A1A1A"];
    }
    return _titleLab;
}

- (ASAvatarGroupMainView *)mainView{
    if (!_mainView) {
        _mainView = [[ASAvatarGroupMainView alloc]initWithFrame:CGRectZero];
        _mainView.backgroundColor = self.contentView.backgroundColor;
    }
    return _mainView;
}

- (ASAvatarGroupTagView *)labelSelect{
    if (!_labelSelect) {
        _labelSelect = [[ASAvatarGroupTagView alloc]initWithFrame:CGRectZero];
        _labelSelect.backgroundColor = self.contentView.backgroundColor;
    }
    return _labelSelect;
}

- (UIButton *)saveBtn{
    if (!_saveBtn) {
        _saveBtn = [UIButton new];
        [_saveBtn setTitle:@"保存全部" forState:UIControlStateNormal];
        [_saveBtn setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
        _saveBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_saveBtn addTarget:self action:@selector(clicksaveBtn) forControlEvents:UIControlEventTouchUpInside];
        [_saveBtn setBackgroundColor:[UIColor colorWithHexString:@"#FF7785"]];
        _saveBtn.layer.masksToBounds = YES;
        _saveBtn.layer.cornerRadius = 15;
    }
    return _saveBtn;
}

- (UIButton *)collectionBtn{
    if (!_collectionBtn) {
        _collectionBtn = [UIButton new];
        [_collectionBtn setTitle:@"收藏全部" forState:UIControlStateNormal];
        [_collectionBtn setTitle:@"已收藏" forState:UIControlStateSelected];
        [_collectionBtn setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
        _collectionBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_collectionBtn addTarget:self action:@selector(clickCollectionBtn) forControlEvents:UIControlEventTouchUpInside];
        [_collectionBtn setBackgroundColor:[UIColor colorWithHexString:@"#FF7785"]];
        _collectionBtn.layer.masksToBounds = YES;
        _collectionBtn.layer.cornerRadius = 15;
    }
    return _collectionBtn;
}

- (UIView *)lineView{
    if (!_lineView) {
        _lineView = [UIView new];
        [_lineView setBackgroundColor:[UIColor colorWithHexString:@"#F2F2F2"]];
    }
    return _lineView;
}

- (void)setModel:(ASHomeMainModel *)model{
    _model = model;
    self.hasShowAlert = NO;
    [self.userIconImage sd_setImageWithURL:[NSURL URLWithString:model.avatar]];
    self.userNameLab.text = model.nickname;
    self.titleLab.text = model.descriptionStr;
    self.mainView.model = model;
    [self.mainView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(model.groupImageH);
    }];
    if (model.is_collect.intValue > 0) {
        self.collectionBtn.selected = YES;
    }else{
        self.collectionBtn.selected = NO;
    }
    
    if (model.tag_arr.count > 0) {
        @weakify(self);
        self.labelSelect.dataArr = model.tag_arr;
        self.labelSelect.hidden = NO;
        [self.labelSelect mas_updateConstraints:^(MASConstraintMaker *make) {
            @strongify(self);
            make.top.mas_equalTo(self.mainView.mas_bottom).mas_offset(15);
            make.height.mas_equalTo(25);
        }];
    }else{
        @weakify(self);
        self.labelSelect.hidden = YES;
        [self.labelSelect mas_updateConstraints:^(MASConstraintMaker *make) {
            @strongify(self);
            make.top.mas_equalTo(self.mainView.mas_bottom);
            make.height.mas_equalTo(0);
        }];
    }
}

- (void)clicksaveBtn{
    [self downLoadData];
}

///下载图片
- (void)downLoadData{
    if (self.model.canSave) {
        [MBProgressHUD showError:@"已下载"];
        return;
    }

    [self addDownLoadTongji];
    [MBProgressHUD showMessage:@"下载中..."];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self.model.picture_urls enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            NSString * subUrl = obj;
            [[SDWebImageManager sharedManager]loadImageWithURL:[NSURL URLWithString:subUrl] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                if (image) {
                    [self saveImage:image];
                }
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showSuccess:@"下载完成"];
        });
    });

//    for (NSString *subUrl in self.model.picture_urls) {
//        [[SDWebImageManager sharedManager]loadImageWithURL:[NSURL URLWithString:subUrl] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
//        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
//            if (image) {
//                [self saveImage:image];
//            }
//        }];
//    }

}

- (void)saveImage:(UIImage *)image{
    FELog(@"asdfsadfsadfasd====%@",image);
    ///开启相册权限
    NSString * title = [ASTool appName];
    [[BDFCustomPhotoAlbum shareInstance]saveToNewThumb:image ifPush:NO subTitle:title showHUD:NO completion:^(BOOL isSucceed, PHAuthorizationStatus photoType) {
        if (!isSucceed) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!self.hasShowAlert) {
                    [self showPhotoAlertView:photoType];
                }
            });
        }else{
            self.model.canSave = YES;
        }
    }];
}

///弹出设置提示
- (void)showPhotoAlertView:(PHAuthorizationStatus)status{
    if (@available(iOS 14.0, *)) {
        if (status == PHAuthorizationStatusLimited) {
            return;
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
    });
    self.hasShowAlert = YES;
    NSString *contentStr = @"请在设置中为我们打开权限，以保存图片";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:contentStr preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alerOne = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        self.hasShowAlert = NO;
    }];
    UIAlertAction *alerTwo = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.hasShowAlert = NO;
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {}];
    }];
    [alert addAction:alerOne];
    [alert addAction:alerTwo];
    [currViewController() presentViewController:alert animated:YES completion:nil];
}


- (void)clickCollectionBtn{
    if (self.clickCollectionBlock) {
        self.clickCollectionBlock(self.model);
    }
}

///下载统计
- (void)addDownLoadTongji{
    [ASHomeApi addDownLoadTongji:self.model.tID completion:^(id  _Nonnull result) {
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)clickUserBtn{
    
}


///收藏数据
- (void)collectionData{
//    [MBProgressHUD showMessage:@"收藏中..."];
//    [IGHomeApi collectionData:self.model.model.tID completion:^(IGBaseModel *  _Nonnull result) {
//        [MBProgressHUD hideHUD];
//        if (result.state.intValue == 1) {
//            self.model.model.iscollect = @"1";
//            self.collectionBtn.selected = YES;
//            [[NSNotificationCenter defaultCenter]postNotificationName:@"FindCollectionData" object:@{@"tID":self.model.model.tID,@"iscollect":self.model.model.iscollect}];
//        }else{
//            [MBProgressHUD showError:result.errorMsg];
//        }
//    } failure:^(NSError * _Nonnull error) {
//        [MBProgressHUD hideHUD];
//        [MBProgressHUD showError:FENETERROR];
//    }];
}

///取消收藏数据
- (void)cancelCollectionData{
//    [MBProgressHUD showMessage:@"取消中..."];
//    [IGHomeApi cancelCollectionData:self.model.model.tID completion:^(IGBaseModel *  _Nonnull result) {
//        [MBProgressHUD hideHUD];
//        if (result.state.intValue == 1) {
//            self.model.model.iscollect = @"0";
//            self.collectionBtn.selected = YES;
//            [[NSNotificationCenter defaultCenter]postNotificationName:@"FindCollectionData" object:@{@"tID":self.model.model.tID,@"iscollect":self.model.model.iscollect}];
//        }else{
//            [MBProgressHUD showError:result.errorMsg];
//        }
//    } failure:^(NSError * _Nonnull error) {
//        [MBProgressHUD hideHUD];
//        [MBProgressHUD showError:FENETERROR];
//    }];
}

@end
